/*  VisualGroup JavaScript prototype Classes, version draf
 *  (c) 2006 Bill Vison <vison_ruan@126.com>
 *
 *
/*--------------------------------------------------------------------------*/
using("Vsg.Chooser");
using("Vsg.Common.Logger");

String.prototype.ellipse = function(maxLength){
    if(this.length > maxLength){
        return this.substr(0, maxLength-3) + '...';
    }
    return this;
};

Vsg.Chooser.ImageChooser = Ext.extend(Ext.util.Observable,{
												
	constructor:function($opt , $attrs) {
		
		var $_attrs = {
			id:"Vsg.Chooser.ImageChooser"
		}
		
		if ($attrs != null) {
			 $_attrs = $attrs;
		}
		//$_attrs.layout = "border";
		//$_attrs.url = $opt.url;
		
		if ($opt == null) {
			throw new Vsg.Chooser.ImageChooser.Exception("没有设定必须参数" ,  null , Vsg.Chooser.ImageChooser.Exception.ParamsNullError);
		}
		
		this.config = {
			url:$opt.url
		}
		

		Vsg.Chooser.ImageChooser.superclass.constructor.call(this,$_attrs);
	},
	
	show:function(el, callback){
		if(!this.win){
			this.initTemplates();
			
			
			// ---- add the data view store ----
			this.store = new Ext.data.JsonStore({
			    url: this.config.url,
			    root: 'images',
			    fields: [
			        'name', 'url',
			        {name:'size', type: 'float'},
			        {name:'lastmod', type:'date', dateFormat:'timestamp'}
			    ],
			    listeners: {
			    	'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
			    }
			});
			this.store.load();
			
			
			
			var formatSize = function(data){
		        if(data.size < 1024) {
		            return data.size + " bytes";
		        } else {
		            return (Math.round(((data.size*10) / 1024))/10) + " KB";
		        }
		    };
			
			var formatData = function(data){
		    	data.shortName = data.name.ellipse(15);
		    	data.sizeString = formatSize(data);
		    	data.dateString = new Date(data.lastmod).format("m/d/Y g:i a");
		    	this.lookup[data.name] = data;
		    	return data;
		    };			
			
		    this.view = new Ext.DataView({
				tpl: this.thumbTemplate,
				singleSelect: true,
				overClass:'x-view-over',
				itemSelector: 'div.thumb-wrap',
				emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
				store: this.store,
				listeners: {
					'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
					'dblclick'       : {fn:this.doCallback, scope:this},
					'loadexception'  : {fn:this.onLoadException, scope:this},
					'beforeselect'   : {fn:function(view){
				        return view.store.getRange().length > 0;
				    }}
				},
				prepareData: formatData.createDelegate(this)
			});
			

			
			// --- file add panel ----
			var $mif =  {
				id:"baseframe",
				xtype:"iframepanel",
				width:"100%",
				border:false,
				loadMask:true,
				frameConfig:{autoCreate:{id:"baseframe" , name:"baseframe",frameborder:0}},
				defaultSrc:"../apps_Filetree/filetree.htm"
			};
			
			var $buttons = []; 
			var $btn = null;
			$btn = {
				id:"btnSelected",
				text:"选 择",
				handler:function() {
					
					// --- set the value ---
					//alert(el.setField);

					
					if ($win != null) {
						$win.hide();
					}
					
				}
			};
			$buttons.push( $btn );
			

			$btn = {
				id:"btnClosed",
				text:"关 闭",
				handler:function() {

					if ($win != null) {
						$win.hide();
					}

				}
			};
			$buttons.push( $btn );
			
			
			// --- add panel ---
			var $panels = [];

			$panels.push({
				id:"img-file-panel",
				region:"west",
				border:false,
				layout:"fit",
				split: true,
				width: 150,
				minWidth: 150,
				maxWidth: 250,
				items:[$mif]
			});

			
			$panels.push({
				id:"img-chooser-view",
				region: 'center',
				autoScroll: true,
				items: [this.view],
				keys: {
					key: 27, // Esc key
					handler: function(){ this.win.hide(); },
					scope: this
				}
			});
			
			$panels.push({
				id: 'img-detail-panel',
				region: 'east',
				split: true,
				width: 150,
				minWidth: 150,
				maxWidth: 250
			});
			

			this.win = new Ext.Window({
				layout:"border",
				width:640,
				height:400,
				closeAction:"hide",
				title:"选择图片",
				buttons:$buttons,
				items:$panels,
				shadow:true,
				modal:true,
				border:false
			});
			var $win = this.win;


		}
		
		try {
			this.win.show(el);
			this.callback = callback;
			this.animateTarget = el;			
		} catch (ex) {
			Vsg.Common.Logger.info("error ex : " + ex);
		}
	},
	
	lookup:{},
	
	initTemplates : function(){
		this.thumbTemplate = new Ext.XTemplate(
			'<tpl for=".">',
				'<div class="thumb-wrap" id="{name}">',
				'<div class="thumb"><img src="{url}" title="{name}"></div>',
				'<span>{shortName}</span></div>',
			'</tpl>'
		);
		this.thumbTemplate.compile();
		
		this.detailsTemplate = new Ext.XTemplate(
			'<div class="details">',
				'<tpl for=".">',
					'<img src="{url}"><div class="details-info">',
					'<b>图片名称:</b>',
					'<span>{name}</span>',
					'<b>尺寸:</b>',
					'<span>{sizeString}</span>',
					'<b>最后更新:</b>',
					'<span>{dateString}</span></div>',
				'</tpl>',
			'</div>'
		);
		this.detailsTemplate.compile();
	},
	
	showDetails : function(){
	    var selNode = this.view.getSelectedNodes();
	    var detailEl = Ext.getCmp('img-detail-panel').body;

		if(selNode && selNode.length > 0){
			selNode = selNode[0];
			/*
			Ext.getCmp('ok-btn').enable();
			*/			
		    var data = this.lookup[selNode.id];
            detailEl.hide();
            this.detailsTemplate.overwrite(detailEl, data);
            detailEl.slideIn('l', {stopFx:true,duration:.2});
		}else{
		    /*
			Ext.getCmp('ok-btn').disable();
			*/
		    detailEl.update('');			
		}
	},
	
	filter : function(){
		var filter = Ext.getCmp('filter');
		this.view.store.filter('name', filter.getValue());
		this.view.select(0);
	},
	
	sortImages : function(){
		var v = Ext.getCmp('sortSelect').getValue();
    	this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
    	this.view.select(0);
    },
	
	reset : function(){
		if(this.win.rendered){
			Ext.getCmp('filter').reset();
			this.view.getEl().dom.scrollTop = 0;
		}
	    this.view.store.clearFilter();
		this.view.select(0);
	},
	
	doCallback : function(){
        var selNode = this.view.getSelectedNodes()[0];
		var callback = this.callback;
		var lookup = this.lookup;
		this.win.hide(this.animateTarget, function(){
            if(selNode && callback){
				var data = lookup[selNode.id];
				callback(data);
			}
		});
    },
	
	onLoadException : function(v,o){
	    this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>'); 
	}	
	
	
});
Vsg.Chooser.ImageChooser.Exception = Ext.extend(Exception.CommonException,{
	name:"Vsg.Chooser.ImageChooser.Exception",
	constructor:function($message , $name ,$value) {
		Vsg.Chooser.ImageChooser.Exception.superclass.constructor.apply(this, arguments);
	}
});
Vsg.Chooser.ImageChooser.Exception.ParamsNullError = 1;
Vsg.Chooser.ImageChooser.Exception.URLNotNullError = 2;


(function() {
	try {
		Interface.ensureImplements(new Vsg.Chooser.ImageChooser({url:"empty"}), Vsg.Chooser);	
	} catch (e) {
		Ext.log("Class Implement Error :"+"[Vsg.Chooser.ImageChooser] , " + e);
	}		  
})();
